import { TemplateFile, templateFile } from "@/api";
import { FormModal } from "@/components";
import { ResultUtil } from "@/util";
import { createAtom, useStore } from "@/util/hooks";
import { Form, Input } from "@arco-design/web-react";
import { useKeyPress } from "ahooks";
import { useRef } from "react";
import {
  TemplateRenameModalStore,
  TemplateFileTree,
  TemplateTreeAtom,
} from "..";

export const TemplateRenameModalAtom = createAtom<TemplateRenameModalStore>({
  open: false,
  type: "update",
  directory: true,
});

export const TemplateRenameModal = () => {
  const [form] = Form.useForm();
  const formRef = useRef(null);
  const modalStore = useStore(TemplateRenameModalAtom);
  const fileTreeStore = useStore(TemplateTreeAtom);

  async function onConfirm() {
    const values: TemplateFile = await form.validate();
    const { clickedKey } = fileTreeStore.value;
    values.id = clickedKey!;
    const res = await templateFile.rename(values);
    if (ResultUtil.showError(res)) {
      modalStore.updateStore({
        open: false,
      });
      TemplateFileTree.init(fileTreeStore);
    }
  }

  useKeyPress(
    "enter",
    () => {
      onConfirm();
    },
    { target: formRef }
  );

  const { directory } = modalStore.value;

  return (
    <FormModal
      atom={TemplateRenameModalAtom}
      fullTitle={directory ? "重命名目录" : "重命名文件"}
      form={form}
      onConfirm={onConfirm}
      autoFocus
    >
      <div ref={formRef}>
        <Form form={form} labelCol={{ span: 5 }}>
          <Form.Item
            label="名称"
            field="fileName"
            requiredSymbol={false}
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </div>
    </FormModal>
  );
};
